import { storeCityList, storeListByDrivingSchool, StorePageProps } from "../../../api/drivingSchool"
import { shareAppMessageSet } from "../../../utils/config"
import { dataCollection } from "../../../utils/dataCollection"
import { listProps, StoreProps } from "../../../utils/type"
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectRegionIndex: 0,
    selectStoreIndex: -1,
    regionList: <{ regionId: string, regionName: string }[]>[],
    coords: {
      latitude: 0,
      longitude: 0,
    },
    drivingSchoolId: '',
    storeData: <listProps>{
      list: [],
      current: 1,
      total: 0
    },
    refresherTriggered: false,
    themeCode: ''
  },
  onLoad(options: any) {
    let drivingSchoolId = options.id
    const city = app.globalData.currentCity
    const regionList: any[] = []

    //从本地获取当前选择的城市编码
    this.setData({
      themeCode: wx.getStorageSync('themeCode')
    })

    storeCityList(options.id, city).then(res => {
      const arr: { value: string, name: string }[] = []
      const store = wx.getStorageSync('selectStore')
      let i = 0
      res.result.forEach((item: any, index: number) => {
        regionList.push({
          regionId: item.regionId,
          regionName: item.regionName
        })
        if (store.regionName === item.regionName) {
          i = index
        }
      })
      this.setData({
        regionList: regionList,
        drivingSchoolId,
        coords: wx.getStorageSync('coords'),
        selectRegionIndex: i
      })
      this.getDataList()
    })

    if (this.timer) {
      clearTimeout(this.timer)
    }
  },
  onSelectRegion(e: any) {
    let index = e.currentTarget.dataset.index
    this.setData({
      selectRegionIndex: index,
      'storeData.current': 1,
      'storeData.list': []
    })
    this.getDataList()

  },
  timer: 0,
  onSelectStore(e: any) {
    let index = e.currentTarget.dataset.index
    wx.setStorage({
      key: 'selectStore',
      data: this.data.storeData.list[index]
    })
    this.setData({ selectStoreIndex: index })
    if (this.timer) {
      clearTimeout(this.timer)
    }
    //选择门店后，0.75s 返回上一页
    this.timer = setTimeout(() => {
      clearTimeout(this.timer)
      wx.navigateBack({ delta: 1 })
    }, 750)
  },
  getDataList(callback = () => { }) {
    if (this.data.regionList.length) {
      wx.setStorageSync('selectRegion', this.data.regionList[this.data.selectRegionIndex])
      const params: StorePageProps = {
        current: this.data.storeData.current,
        size: 10,
        regionId: this.data.regionList.length ? this.data.regionList[this.data.selectRegionIndex].regionId : '',
        schoolId: this.data.drivingSchoolId,
        lat: Number(this.data.coords.latitude),
        lng: Number(this.data.coords.longitude)
      }
      storeListByDrivingSchool(params).then(res => {
        const list: StoreProps[] = this.data.storeData.list
        if (this.data.storeData.current === 1) {
          list.length = 0
        }
        const arr: any[] = res.result.records
        const store = wx.getStorageSync('selectStore')
        let selectIndex = -1
        arr.forEach((item: StoreProps, index: number) => {
          const dist = Number(item.distance).toFixed(2)
          item.distance = Number(dist) < 1 ? (Number(dist) * 1000 + 'm') : (Number(dist) + 'km')
        })

        list.push(...arr)

        list.forEach((item: StoreProps, index: number) => {
          if (store && store.id === item.id) {
            selectIndex = index
            console.log(item)
          }
        })

        let index = this.data.storeData.current
        index++

        const obj: listProps = {
          current: index,
          list: [...list],
          total: res.result.total
        }
        this.setData({
          storeData: obj,
          selectStoreIndex: selectIndex,
        })
        callback()
      })
    }

  },
  bindrefresherpulling(res: any) {
    console.log('bindrefresherpulling', res)
  },
  bindrefresherrefresh(res: any) {
    console.log('bindrefresherrefresh', res)
    this.setData({
      refresherTriggered: true,
      'storeData.current': 1
    })
    this.getDataList(() => {
      this.setData({
        refresherTriggered: false
      })
    })
  },
  bindrefresherrestore(res: any) {
    console.log('bindrefresherrestore', res)
  },
  bindrefresherabort(res: any) {
    console.log('bindrefresherabort', res)
  },
  bindscrolltolower(res: any) {
    console.log('bindscrolltolower', res)
    if (this.data.storeData.list.length < Number(this.data.storeData.total)) {
      this.getDataList()
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return { ...shareAppMessageSet() }
  },
  onHide() {
    dataCollection.setPageMapData('leave')
  },
  onUnload() {
    dataCollection.setPageMapData('leave')
  },
  onShow() {
    dataCollection.setPageMapData('enter', '门店列表')
  },
})